package com.ifox.frame;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Map;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

import org.jvnet.substance.skin.SubstanceBusinessBlackSteelLookAndFeel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ifox.common.MyDefaultTableModel;
import com.ifox.entity.IFox;
import com.ifox.util.Utils;

public class ListFrame extends JFrame {

	private static final long serialVersionUID = 7640088701143396844L;
	public static IFox ifox = null;
	public static boolean isAdd = true;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	private JPanel contentPane;
	private JTable tbFileList;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ListFrame frame = new ListFrame();
					frame.setLocationRelativeTo(null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ListFrame() {
		setName("mainFrame");
		setTitle("交换接口管理");
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 600, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		contentPane.add(toolBar);
		
		JButton btnAdd = new JButton("新增");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ifox = new IFox();
				isAdd = true;
				DataSourceFrame frame = new DataSourceFrame(ListFrame.this,true);
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
				refreshTable();
			}
		});
		btnAdd.setFont(new Font("宋体", Font.PLAIN, 12));
		toolBar.add(btnAdd);
		
		JButton btnEdit = new JButton("修改");
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doEdit();
			}
		});
		toolBar.add(btnEdit);
		
		JButton btnDel = new JButton("删除");
		btnDel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int row = tbFileList.getSelectedRow();
				if(row<0){
					JOptionPane.showMessageDialog(null, "请先选中一行再使用该功能！" , "信息", JOptionPane.WARNING_MESSAGE);
				}else{
					String filename = tbFileList.getValueAt(row, 0).toString();
					int answer = JOptionPane.showConfirmDialog(null, "真的要删除【" + filename + "】这个配置文件吗？" , "信息", JOptionPane.WARNING_MESSAGE);
					if(answer==JOptionPane.YES_OPTION){
						Utils.delFile(filename);
						refreshTable();
					}
				}
			}
		});
		toolBar.add(btnDel);
		
		JButton btnRefresh = new JButton("刷新");
		btnRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshTable();
			}
		});
		toolBar.add(btnRefresh);
		
		JButton btnQuit = new JButton("退出");
		btnQuit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(NORMAL);
			}
		});
		toolBar.add(btnQuit);
		contentPane.add(toolBar, BorderLayout.NORTH);
		
		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		tbFileList = new JTable();
//		tbFileList.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		tbFileList.getTableHeader().setReorderingAllowed(false);
		tbFileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tbFileList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2){
					doEdit();
                }
			}
		});
		refreshTable();
		scrollPane.setViewportView(tbFileList);
		try {
			UIManager.setLookAndFeel(new SubstanceBusinessBlackSteelLookAndFeel());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	private Vector<String> getHeader(){
		String[] columnNames = { "名称", "文件名", "交换表数量" };
		Vector<String> header = new Vector<String>();

		for (int i = 0; i < columnNames.length; i++) {
			header.add(columnNames[i]);
		}
		return header;
	}
	
	private Vector<Vector<String>> getRow(){
		Map<String,String> files = Utils.getFiles();
		Vector<Vector<String>> row = new Vector<Vector<String>>();
		Vector<String> cell;
		for (String key : files.keySet()) {
			IFox tmpFox = Utils.openIFox(key);
			cell = new Vector<String>();
			cell.add(key);
			cell.add(files.get(key));
			cell.add(tmpFox.getTables().size()+"");
			row.add(cell);
			tmpFox = null;
		}
		return row;
	}
	
	private TableModel getTableModel(){
		MyDefaultTableModel tablmod = new MyDefaultTableModel();
		tablmod.setDataVector(getRow(), getHeader());
		return tablmod;
	}
	
	private void doEdit(){
		int row = tbFileList.getSelectedRow();
		if(row<0){
			JOptionPane.showMessageDialog(null, "请先选中一行再使用该功能！" , "信息", JOptionPane.WARNING_MESSAGE);
		}else{
			String filename = tbFileList.getValueAt(row, 0).toString();
			isAdd = false;
			ListFrame.ifox = Utils.openIFox(filename);
			DataSourceFrame frame = new DataSourceFrame(ListFrame.this,true);
			frame.setLocationRelativeTo(null);
			frame.setVisible(true);
		}	
	}
	
	private void refreshTable(){
		tbFileList.setModel(getTableModel());
		tbFileList.getColumnModel().getColumn(0).setPreferredWidth(150);
		tbFileList.getColumnModel().getColumn(1).setPreferredWidth(300);
		DefaultTableCellRenderer render = new DefaultTableCellRenderer();
		render.setHorizontalAlignment(SwingConstants.CENTER);
		tbFileList.getColumn("名称").setCellRenderer(render);
		tbFileList.getColumn("交换表数量").setCellRenderer(render);
		tbFileList.validate();
		tbFileList.repaint(); 
	}
}
